// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package user

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"context"
	"database/sql"
	"encoding/json"
	"errors"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(req *types.UserUpdatePassWordReq) (resp bool, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	usersModel := model.NewUsersModel(l.svcCtx.Conn)
	user, err := usersModel.FindById(l.ctx, userId)
	if err != nil || errors.Is(err, sql.ErrNoRows) {
		_ = errors.New("用户不存在")
	}
	password := req.Password
	oldPassword := req.OldPassword
	if password == "" && oldPassword == "" {
		return false, errors.New("密码不能为空")
	}
	if !sqlutil.CheckPasswordHash(oldPassword, user.Password) {
		return false, errors.New("旧密码错误")
	}
	hashPassword, err := sqlutil.HashPassword(password)
	if err != nil {
		return false, errors.New("密码加密失败")
	}
	user.Password = hashPassword
	err = usersModel.Update(l.ctx, user)
	if err != nil {
		return false, errors.New("密码修改失败")
	}
	return true, nil
}
